package usercenter

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"navi-mumbai/common/gensql"
	"time"
)

var _ ApkConfigModel = (*customApkConfigModel)(nil)

type (
	// ApkConfigModel is an interface to be customized, add more methods here,
	// and implement the added methods in customApkConfigModel.
	ApkConfigModel interface {
		apkConfigModel
		Find(ctx context.Context, id int64, version string, start, end *time.Time, page, pageSize int64) ([]*ApkConfig, error)
		Count(ctx context.Context, id int64, start, end *time.Time) (int64, error)
	}

	customApkConfigModel struct {
		*defaultApkConfigModel
		genSql *gensql.GenSql
	}
)

func (m customApkConfigModel) Find(ctx context.Context, id int64, version string, start, end *time.Time, page, pageSize int64) ([]*ApkConfig, error) {
	q := fmt.Sprintf("select %s from %s ", apkConfigRows, m.table)
	m.genSql.InitSql(q)
	if id > 0 {
		m.genSql = m.genSql.Where("id  =  ?", id)
	}

	if version != "" {
		m.genSql = m.genSql.Where("version  =  ?", version)
	}

	if start != nil {
		m.genSql = m.genSql.Where("create_time >= ?", start)
	}
	if end != nil {
		m.genSql = m.genSql.Where("create_time <= ?", end)
	}
	// 分页
	if page < 1 {
		page = 1
	}
	if pageSize <= 0 {
		pageSize = 10
	}
	m.genSql = m.genSql.OrderBy("create_time desc").Limit(uint64(pageSize)).Offset(uint64((page - 1) * pageSize))
	query, values, err := m.genSql.ToSql()
	if err != nil {
		return nil, err
	}
	resp := make([]*ApkConfig, 0)
	err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
	switch err {
	case nil:
		return resp, nil
	default:
		return nil, err
	}
}

func (m *customApkConfigModel) Count(ctx context.Context, id int64, start, end *time.Time) (int64, error) {
	q := fmt.Sprintf("select count(id) from %s ", m.table)
	m.genSql.InitSql(q)

	if id > 0 {
		m.genSql = m.genSql.Where("id  =  ?", id)
	}

	if start != nil {
		m.genSql = m.genSql.Where("create_time >= ?", start)
	}
	if end != nil {
		m.genSql = m.genSql.Where("create_time <= ?", end)
	}

	query, values, err := m.genSql.ToSql()
	if err != nil {
		return 0, err
	}
	var resp int64
	err = m.QueryRowNoCacheCtx(ctx, &resp, query, values...)
	switch err {
	case nil:
		return resp, nil
	default:
		return 0, err
	}
}

// NewApkConfigModel returns a model for the database table.
func NewApkConfigModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) ApkConfigModel {
	return &customApkConfigModel{
		defaultApkConfigModel: newApkConfigModel(conn, c, opts...),
		genSql:                gensql.NewGenSql(),
	}
}
